package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
	"github.com/gorilla/mux"
	"github.com/gorilla/handlers"
)
var c = make(chan string, 10)
var f, err = os.OpenFile("gotest11.txt", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)

func main() {
	var router = mux.NewRouter()
	router.HandleFunc("/healthcheck", healthcheck).Methods("GET")
	router.HandleFunc("/message",handelQryMessage).Methods("GET")
	router.HandleFunc("/m/{msg}",handelUrlMessage).Methods("GET")

	headersOk := handlers.AllowedHeaders([]string{"Authorization"})
	originsOk := handlers.AllowedOrigins([]string{"*"})
	methodsOk := handlers.AllowedMethods([]string{"GET", "POST", "OPTIONS"})

	fmt.Println("Running server")
	log.Fatal(http.ListenAndServe(":2000",  handlers.CORS(originsOk, headersOk, methodsOk)(router)))

	check(err)
	defer f.Close()
}

func check(e error) {
	if e != nil {
		panic(e)
	}
}


func handelQryMessage(w http.ResponseWriter, r *http.Request)  {
	vars := r.URL.Query();
	message := vars.Get("msg")
	c <- message
	go wfile()
	json.NewEncoder(w).Encode(map[string]string{"message":message})
}

func handelUrlMessage(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	message := vars["msg"]
	c <- message
	go wfile()
	json.NewEncoder(w).Encode(map[string]string{"message": message})
}



func healthcheck(w http.ResponseWriter, r *http.Request) {
	json.NewEncoder(w).Encode("Still alive")
}

func wfile() {
	f.WriteString(<-c)
	f.WriteString("\n")
}